import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { ButtonDefineType, DialogType, EInputDataType, EventExcuteType, TabFieldType } from '../../DataStructs/commontype';
import { httpReqeustApi } from '/@/api/linxyun/base';
import exportExcel from '/@/utils/exportExcel.js';
// import { calcFieldValue } from '/@/utils/formatPrivacyData.js';
import { calcFieldValue } from '/@/components/Linxyun/custom/CustomCommon/lxy_expression.js';

import type { IStateType, IPropsType } from '../type';

const httpRequest = httpReqeustApi();

export default function useBtnOperate(getData: () => void, state: IStateType, props: IPropsType) {
	const router = useRouter();
	// 删除行
	const handleDeleteRow = (btnDefine: ButtonDefineType, row: Record<string, any>) => {
		console.log('handleDeleteRow', row);

		if (row?.isTabTempData) {
			if (row.index === undefined) return;
			console.log('handleDeleteRow index', row.index);
			const tempArr = state.pageData.tableData.splice(row.index, 1);

			return;
		}
		if (!btnDefine.NeedComfirm) {
			const loading = ElLoading.service({ lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)' });
			httpRequest.Post(btnDefine.SubmitUrl, row).then((res: any) => {
				if (!res.success) {
					ElMessage({
						message: '删除失败！',
						type: 'error',
						duration: 5 * 1000,
					});
					loading.close();
					return;
				}
				ElMessage({
					message: '删除成功',
					type: 'success',
					duration: 5 * 1000,
				});
				loading.close();
				getData();
				return;
			});
		} else {
			ElMessageBox.confirm('确定要该条删除？', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(async () => {
					const loading = ElLoading.service({ lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)' });
					console.log('删除', row);
					const res: any = await httpRequest.Post(btnDefine.SubmitUrl, row);
					if (!res.success) {
						ElMessage({
							message: '删除失败！',
							type: 'error',
							duration: 5 * 1000,
						});
						loading.close();
						return;
					}
					ElMessage({
						message: '删除成功',
						type: 'success',
						duration: 5 * 1000,
					});
					loading.close();
					getData();
				})
				.catch(() => {
					ElMessage.info('已取消删除');
				});
		}
	};

	const exCelFlag = ref(false);
	// 导出Excel
	const handleExportExcel = async (
		tableShowDefines: TabFieldType[],
		url: string,
		formData: Record<string, any>,
		getViewData: (fieldDefine: Record<string, any>, value: string) => any,
		params: Record<string, unknown>
	) => {
		if (!exCelFlag.value) {
			exCelFlag.value = true;
			console.log('导出');
			const exportData = await queryExportData({ current: 1, limit: 20, ...params });
			if (!exportData) {
				console.warn('exportExcel exportData', exportData);
				return;
			}
			console.log('exportExcel exportData', exportData);

			if (tableShowDefines.length < 1) {
				console.error('[Error][ExportExcel]No table col define.');
				return;
			}
			const newTableData: any[] = [];
			// 格式化某些字段
			console.log('tableShowDefines', tableShowDefines);
			for (let d = 0; d < exportData.length; d++) {
				const keys: string[] = Object.keys(exportData[d]);
				const item: any = {};

				for (let td = 0; td < tableShowDefines.length; td++) {
					console.log(tableShowDefines[td]);
					if (!tableShowDefines[td].FieldName && !tableShowDefines[td].FieldIndex) continue;
					if (keys.indexOf(tableShowDefines[td].FieldName) !== -1) {
						const value = getViewData(tableShowDefines[td], exportData[d][tableShowDefines[td].FieldName]);
						exportData[d][tableShowDefines[td].FieldName] = value;
					}
					item[tableShowDefines[td].FieldName] = exportData[d][tableShowDefines[td].FieldName];
				}
				newTableData.push(item);
			}

			console.log('new exportExcel exportData', newTableData, tableShowDefines);
			const titleArr = tableShowDefines.map((tableDefine: TabFieldType) => {
				return tableDefine.Label;
			}); //表头中文名

			console.log('titleArr', newTableData, formData.FileName, titleArr, formData.SheetName);
			exportExcel(newTableData, formData.FileName, titleArr, formData.SheetName);
			exCelFlag.value = false;
		} else {
			ElMessage.warning('正在导出，请勿重复操作!');
		}
		// 请求需要打印的数据
		async function queryExportData(params: Record<string, any>) {
			if (!url) {
				console.error('[Error]No set search event url, can not export data.');
				return null;
			}

			// params.current = 1
			// params.limit = 2
			const datas = [];
			while (true) {
				const res: any = await httpRequest.Post(url, { ...params });
				if (!res || res.code !== '0000') {
					console.error('[Error]Query export data fail, param: ', params);
					break;
				}
				if (!res.Records) {
					break;
				}
				datas.push(...res.Records);
				if (res.Records.length < params.limit) {
					break;
				}
				params.current++;
			}

			return datas;
		}
	};
	// 导入Excel
	const handleImportExCel = () => {
		console.log('导入Excel');
	};

	// 搜索
	const handleSearch = () => {
		console.log('handleSearch ', state.queryParams);
		// 搜索的时候把页码设置为 1
		state.pageData.current = 1;
		state.pageConfig.currentPage = 1;
		getData();
		// refInfo.value['lx_input1'].setActivate({ activate: false });
	};
	// 重置
	const handleReset = () => {
		Object.keys(state.queryParams).forEach((key) => {
			state.queryParams[key] = '';
		});
		handleSearch();
		console.log(state.queryParams);
	};

	interface btnDefineE extends ButtonDefineType {
		type?: string;
		index?: number;
		PageID?: number | null;
	}

	// 自定义
	const handleCustomize = (
		btnDefine: btnDefineE,
		OpType: DialogType,
		row: Record<string, any> | undefined,
		multipleSelection: Record<string, any>[]
	) => {
		const ot = btnDefine.EventDefine!.OpType;
		const Params = btnDefine.EventDefine!.Params;
		console.log('handleCustomize Params:', Params);
		const newParams: Record<string, any> = {};
		if (Params && Array.isArray(Params)) {
			for (const item of Params) {
				const value = calcFieldValue(
					row ? 4 : item.InputDataType,
					item.ParamVal,
					props.inputData,
					{ ...state.pageData, ...(row || {}) },
					state.globalData
				);
				newParams[item.ParamKey] = value;
			}
		}

		if (ot === EventExcuteType.Function) {
			console.log('执行函数');
		} else if (ot === EventExcuteType.Jump) {
			console.log('跳转', btnDefine);
			let from = '';
			if (btnDefine.type && btnDefine.PageID && btnDefine.index !== undefined) {
				from = `table_${btnDefine.PageID}_${btnDefine.type}_${btnDefine.index}`;
				sessionStorage.setItem(from, JSON.stringify({ ...newParams, row: row || {} }));
			}

			router.push({
				path: btnDefine.SubmitUrl,
				query: { from: from },
			});
		} else if (ot === EventExcuteType.Customizepage || ot === EventExcuteType.TablePage) {
			const { DialogDefine } = btnDefine.EventDefine!;
			state.dialogConfig.title = btnDefine.Title;
			state.dialogConfig.opType = OpType;
			state.dialogConfig.ot = ot;
			state.dialogConfig.submitUrl = btnDefine.SubmitUrl; // pageid
			state.dialogConfig.width = DialogDefine.Width || 'auto';
			state.dialogConfig.superiorParams = newParams;
			state.dialogConfig.formData = JSON.parse(JSON.stringify({ ...newParams, ...row }));
			state.showDialog = true;
			state.dialogConfig.fromPageID = btnDefine.PageID || -1;
			console.log('自定义表单或页面', DialogDefine);
		} else if (ot === EventExcuteType.Interface) {
			if (row === undefined) {
				if (multipleSelection.length === 0) {
					ElMessage.error('请至少勾选一个');
					return;
				}
				const params: {
					Records: Record<string, any>[];
				} = {
					Records: [],
				};
				params.Records = multipleSelection.map((item) => {
					return { ...item, ...newParams };
				});
				httpRequest.Post(btnDefine.SubmitUrl, {}, params).then((res) => {
					if (res.success) {
						getData();
						ElMessage.success('批量操作成功');
					} else {
						ElMessage.error('批量操作失败');
					}
				});
			} else {
				ElMessageBox.confirm('是否进行该操作', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				})
					.then(() => {
						httpRequest.Post(btnDefine.SubmitUrl, {}, { ...newParams }).then((res) => {
							if (res.success) {
								getData();
								ElMessage.success('操作成功');
							} else {
								ElMessage.error('操作失败');
							}
						});
					})
					.catch(() => {
						ElMessage({
							type: 'info',
							message: '已取消',
						});
					});
			}
		}
	};

	// 控制按钮的显示隐藏
	const handleShowBtn = computed(() => (btnDefine: ButtonDefineType, row?: Record<string, any>, length?: number) => {
		// 没有过滤条件隐藏查询按钮
		if (
			btnDefine.ShowLocal === 'query' &&
			btnDefine.EventDefine?.OpType === EventExcuteType.Inner &&
			btnDefine.EventDefine.DialogDefine.OpType === DialogType.query &&
			length === 0
		) {
			return false;
		}
		let newRow = {};
		if (row) {
			newRow = row;
		}
		const inputData = { ...props.inputData, ...newRow };
		if (!btnDefine.ShowCtrl) {
			return true;
		}
		const res = calcFieldValue(EInputDataType.Exp, btnDefine.ShowCtrl, inputData, state.pageData, state.globalData);
		try {
			return new Function(`return ${res}`)();
		} catch (e) {
			console.log(e);
			return res;
		}
	});
	return {
		handleDeleteRow,
		handleExportExcel,
		handleImportExCel,
		handleReset,
		handleSearch,
		handleCustomize,
		handleShowBtn,
	};
}
